<template>
    <div class="back">
        <el-row>
            <el-col :span="8" class="col1">
            <el-avatar
            :src="userInfo.avatar"
            style="width: 120px;height: 120px;margin-top: 30px;"
        />
        <span class="user-name">{{ userInfo.name }}</span>
        <p class="user-place">登录地址: &nbsp; &nbsp; &nbsp;{{ address }}</p></el-col>
    <el-col :span="16">
      <el-row>
        <el-col :span="5" class="all_col">
          <el-row class="all_row" style="background-color: rgb(46, 199, 201 );">
            <el-icon color="#fff" size="40" class="all_icon"><Warning /></el-icon>
          </el-row>
          <el-row class="all_num">
            {{ status['待支付'] ? status['待支付'] :0}}
          </el-row>
          <span class="text">今日待支付订单</span>
          
        </el-col>
        <el-col :span="5" class="all_col"><el-row class="all_row" style="background-color: rgb(255, 183, 128 );">
            <el-icon color="#fff" size="40" class="all_icon"><Refresh /></el-icon>
          </el-row>
          <el-row class="all_num">
            {{ service['未接单'] ? service['未接单'] :0}}
          </el-row>
          <span class="text">今日未接单订单</span></el-col>
        <el-col :span="5" class="all_col"><el-row class="all_row" style="background-color: rgb(89, 177, 240 );">
            <el-icon color="#fff" size="40" class="all_icon"><CircleCheck /></el-icon>
          </el-row>
          <el-row class="all_num">
            {{ status['已完成'] ? status['已完成'] :0}}
          </el-row>
          <span class="text">今日已完成订单</span></el-col>
        <el-col :span="5" class="all_col"><el-row class="all_row" style="background-color: rgb(223, 171, 61)">
            <el-icon color="#fff" size="40" class="all_icon"><CircleClose /></el-icon>
            
          </el-row>
          <el-row class="all_num">
            {{ status['已取消'] ? status['已取消'] :0}}
          </el-row>
          <span class="text">今日已取消订单</span></el-col>
      </el-row>
    </el-col>
  </el-row>
  <el-row style="margin-top: 9px;">
    <el-col :span="8">
    <h2 class="infor">客户信息</h2>
      <el-table :data="tableData.list" style="height: 450px;margin-top: 20px">
        <el-table-column label="下单时间">
            <template #default="scope">
            <span>{{ scope.row.order_start_time }}</span>
            </template>
        </el-table-column>
        <el-table-column prop="client.name" label="姓名"/>
        <el-table-column prop="receiveAddress" label="地址"/>
      </el-table>
    </el-col>
    <el-col :span="16">
      <h2 class="infor">陪护师业绩排行</h2>
      <div
    ref="myChart1"
    id="myChart1"
    :style="{ width: '810px', height: '220px' }">
  </div>
    <el-row>
      <el-col :span="12">
        <h2 class="infor" style="margin-bottom: 10px;">医院就诊比例</h2>
        <div
        ref="myChart2"
        id="myChart2"
        :style="{ width: '400px', height: '220px'}"
    >
  </div></el-col>
      <el-col :span="12">
        <el-calendar ref="calendar">
    <template #header="{ date }">
      <span>{{ date }}</span>
    </template>
  </el-calendar>
      </el-col>
    </el-row>
    </el-col>
  </el-row>
    </div>
   
</template>

<script setup>
      import dayjs from 'dayjs';
      import { onMounted,getCurrentInstance, reactive, ref } from 'vue';
      import {getOrderList} from '../../api/order/index'
      //导入封装的storge方法
      import Storage from '../../local/index'
      const userInfo=JSON.parse(Storage.getItem('userInfo'))

      const { proxy  } = getCurrentInstance();
      //获得全局配置
      const echarts = proxy.$echarts

      //日期展示定义
      const calendar = ref()
      const selectDate = (val) => {
        calendar.value.selectDate(val)
      }
      
      const address = ref('')
      const param = reactive({
        pageNum:1,
        pageSize:10
      })

      // 获取ip所在城市、区等信息
      const getIPCity=()=> {
      var data = {
        key: 'KSPBZ-V5L33-5EM3D-35N5X-DIY66-CRF7J', //密钥
      }
      var url = 'https://apis.map.qq.com/ws/location/v1/ip' //腾讯地理位置信息接口
      data.output = 'jsonp' // 解决跨域问题
      proxy.$jsonp(url, data).then((res) => {
        address.value=`${res.result.ad_info.province}-${res.result.ad_info.city}-${res.result.ad_info.district}`
        // console.log(address);
        return res
      }).catch((error) => {
        
      })
    }
    //定义要展示的数据
    const status = ref({})
    const service = ref({})
    const hospitals = ref({})
    const companions = ref({})
    const statuskey = 'trade_state'
    const servicekey = 'service_state'
    const hospkey = 'hospital_name'
    const companionskey = 'companion.name'

    //定义柱状图数据
    const xDa = ref([])
    const yDa = ref([])
    
    //获取客户信息
    const tableData = reactive({
        list:[]
    })

    onMounted(()=>{
      
      //获取位置
        getIPCity()
        getOrderList(param).then(({data})=>{
          // console.log(data.data.list);
          const {list}= data.data
          list.forEach(item => {
            item.order_start_time = dayjs(item.order_start_time).format('YYYY-MM-DD')
        });
        tableData.list = list
          // console.log(list);
          status.value = getNum(list,statuskey)
          service.value = getNum(list,servicekey)
          hospitals.value = getNum(list,hospkey)
          companions.value = getNum(list,companionskey)
          xDa.value = Object.keys(companions.value).splice(0,5)
          yDa.value = Object.values(companions.value).splice(0,5)
          //柱形图渲染数据
          getEchart(xDa.value,yDa.value)
          getPie(Object.entries(hospitals.value).map(([name, value]) => ({name, value})))

        })
    })
    
    //封装方法，得到特定属性出现的数量
    const getNum = (list,propname)=>{
      const obj = {}
      //如果是对象包对象的形式,进行分割
      const pathParts = propname.split('.')
      // console.log(list,propname);
      list.forEach(item => {
        let value = item //获得每一个对象
        for(let part of pathParts){
          if(value && part in value){ //判断是否是对象包对象格式
            value = value[part] //获取第二层对象
          }else{
            value = undefined;
            break
          }
        }
        if(value !== undefined){
          if (obj[value]) {  
            obj[value]++;  
        } else {  
            obj[value] = 1;  
        }  
        }
      });
      return obj
    }
    //封装方法，渲染echarts图表,陪护师柱形图
    const getEchart =(xDate,yDate)=>{
      const dom = document.getElementById('myChart1');
      const myChart = echarts.init(dom); // 初始化echarts实例
      const option = {
        tooltip: {
					trigger: 'axis', //坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用
					axisPointer: {// 坐标轴指示器，坐标轴触发有效
						type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
					}
        },

        xAxis: {
          type: 'category',
          data: ['张静', '李喜喜', '王伟', '梁灵', '王文', '赵权', '孙婷'],
          name:'姓名'
        },
        yAxis: {
          type: 'value',
          name:'业绩'
        },
        series: [
          {
            data:  [23, 24, 18, 25, 27, 28, 25],
            itemStyle:{
            color: '#91cc75'
          },
            type: 'bar',
          }
        ]
      };
      // 设置实例参数
      myChart.setOption(option);
    }

    //封装饼图
    const getPie = (data)=>{
      const dom2 = document.getElementById('myChart2');
      const myChart = echarts.init(dom2); // 初始化echarts实例
      const option = {
        tooltip: {//提示框组件
					trigger: 'item', //item数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用。
					axisPointer: {
						// 坐标轴指示器，坐标轴触发有效
						type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
					},
					formatter: '{a} <br/>{b} : {c} <br/>百分比 : {d}%' //{a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
},
  series: [
    {
      type: 'pie',
      data: data,
      name:'就诊医院'
    }
  ]
};
// 设置实例参数
myChart.setOption(option);
    }
</script>

<style lang="less" scoped>
    .col1{
        background-color: rgb(255, 255, 255);
        height: 200px;
        border-radius: 10px;
    }
    .user-name{
        margin-left: 74px;
        top: 40%;
        position: absolute;  
    }
    .user-place{
        margin-left: 25px;
        margin-top: 10px;
    }
    .all_col{
      background-color: rgb(255, 255, 255);
        height: 200px;
        width: 150px;
        margin-left: 15px;
        border-radius: 10px;
        .all_row{
          width: 100%;
          height: 30%;
          border-radius: 10px;
        }
    }
    .all_icon{
      margin-left: 57px;
      margin-top: 10px;
}
.all_num{
  font-size: 30px;
  margin-left: 67px;
  margin-top: 40px;
  }
  .text{
    display: block;
    margin-top: 35px;
    margin-left: 25px;
    color: gray;
    font-size: 15px;
  }
  .infor{
    text-align: center;
  }
  :deep .el-calendar-table .el-calendar-day {
  width: 100%;
  height: 30px;
  text-align: center;
}
</style>